import { getRequestId } from '@/utils/tools'

export default {

    async getTargetComment(commentId) {
        const db = this.database();
        const commentCol = db.collection('comment');
        let res = await commentCol.where({
            commentId
        }).get()
        if (res.data.length > 0) {
            return res.data[0]
        } else {
            let item = {
                commentId,
                list: []
            }
            await commentCol.add(item)
            return item
        }
    },

    async postComment({ commentId, content, option }) {
        const db = this.database();
        const commentCol = db.collection('comment');

        let userInfo = wf.getModule('store').state.userInfo

        let body = {
            cid: getRequestId(),
            content,
            option,
            timeStamp: new Date().getTime(),
            userInfo: {
                uid: userInfo.uid,
                avatarUrl: userInfo.avatarUrl,
                nickName: userInfo.nickName,
                gender: userInfo.gender,
                email: userInfo.email,
                location: userInfo.location,
                avatarImg: userInfo.avatarImg,
            },

            subComments: [],

            likes: []
        }

        let res = await commentCol.where({
            commentId
        }).get()

        const target = res.data[0]

        let { list, _id } = target;

        const type = option.type;

        if (type === 'toPost') {
            list.push(body)
        }
        console.log('target', list, _id);

        return commentCol.doc(_id).update({
            list
        })
    },

    async likeComment(commentId, cid) {
        const db = this.database();
        const commentCol = db.collection('comment');



        let res = await commentCol.where({
            commentId
        }).get()

        let comments = res.data[0].list;

        const _id = res.data[0]._id

        comments.forEach(c => {
            if (c.cid === cid) {

                let isLike = false
                let uid = wf.getModule('store').state.userInfo.uid

                for (let i = 0; i < c.likes.length; i++) {
                    const user = c.likes[i];
                    if (user.uid === uid) {
                        isLike = true
                    }

                }
                if (!isLike) {
                    c.likes.push({
                        uid: wf.getModule('store').state.userInfo.uid
                    })
                }

                console.log('likeComment', comments);
            }
        })

        return commentCol.doc(_id).update({
            list: comments
        })



    }


};
